package com.guagua.vas.redis;


import java.util.Map;

import org.apache.log4j.Logger;

import com.guagua.vas.constants.CacheConstants;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedIsService {
	
	static Logger logger = Logger.getLogger(RedIsService.class.getName());
	
	private static JedisPool jedisPool = null;
	
	private static Jedis jedis = null;
	
	private static JedisPoolConfig jedisPoolConfig = null;
		
	private static boolean initialized = false;	
	
	private RedIsService(){}
	public static Jedis getJedisInstance(){
		if(!initialized){
			startJedis();
		}
		return jedis;
	}
	
	public static Map<String,String> getJedisByKey(String key){
		if(!initialized){
			startJedis();
		}
		jedis = jedisPool.getResource();
		Map<String,String> map = jedis.hgetAll(key);
		jedisPool.returnResource(jedis);
		return map;
	}
	public static String getByKey(String key){
		if(!initialized){
			startJedis();
		}
		jedis = jedisPool.getResource();
		String  str= jedis.get(key);
		jedisPool.returnResource(jedis);
		return str;
	}
	public static synchronized void startJedis(){
	  if(!initialized){
		try{
			String ipPort[] = CacheConstants.REDIS_IP_PORT.split(",");
			jedisPoolConfig = new JedisPoolConfig(); 
			jedisPoolConfig.setMaxActive(100000);
			jedisPoolConfig.setMaxIdle(200);
			jedisPoolConfig.setMaxWait(1000L);
			jedisPoolConfig.setTestOnBorrow(true);
			jedisPool = new JedisPool(jedisPoolConfig,ipPort[0],Integer.parseInt(ipPort[1]));
			initialized = true;
		}catch(Exception e){
			logger.error("redis 初始化失败!"+e,e);
	    }
	  }
	}
}